﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CinemaWS.Model;
using CinemaWS.Model.CustomEntities;

namespace CinemaWS.Repository
{
    public class TicketInfoRepository
    {
        private static CinemaServiceEntities dataEntities = new CinemaServiceEntities();

        private static TicketInfoEntity ConvertToEntity(TicketInfo ticketInfo)
        {
            return new TicketInfoEntity
            {
                ID = ticketInfo.ID,
                ImageUrl = ticketInfo.ImageUrl,
                Fare = ticketInfo.Fare.HasValue ? ticketInfo.Fare.Value : 0,
                Version = ticketInfo.Vesion,
                DayOfWeek = ticketInfo.DayOfWeek,
                StartedTime = ticketInfo.StartedTime,
                EndedTime = ticketInfo.EndedTime,
                Subject = ticketInfo.Subject,
                Type = ticketInfo.Type,
                CinemaFK = CinemaRepository.ConvertToEntity(ticketInfo.Cinema)
            };
        }

        private static TicketInfoEntity[] ConvertToArray(List<TicketInfo> list)
        {
            TicketInfoEntity[] ticketInfoList = new TicketInfoEntity[list.Count()];
            for (int i = 0; i < list.Count(); i++)
            {
                Add(i, ticketInfoList, ConvertToEntity(list[i]));
            }
            return ticketInfoList;
        }

        private static void Add(int index, TicketInfoEntity[] list, TicketInfoEntity ticketInfo)
        {
            list[index++] = ticketInfo;
        }

        public static TicketInfoEntity[] GetAll()
        {
            try
            {
                var list = dataEntities.TicketInfo.ToList();
                return ConvertToArray(list);
            }
            catch
            {
                return null;
            }
        }

        // Maybe need to use?
        public static TicketInfoEntity[] GetAllByCinema(int cinemaID)
        {
            try
            {
                var list = dataEntities.TicketInfo.Where(ti => ti.Cinema.ID == cinemaID).ToList();
                return ConvertToArray(list);
            }
            catch
            {
                return null;
            }
        }

        public static string[] GetImagesOfTicketInfoByCinema(int cinemaID)
        {
            try
            {
                var ticketInfo = dataEntities.TicketInfo.Where(tk => tk.CinemaID == cinemaID).First();
                string s = ticketInfo.ImageUrl;
                if (s.Trim().Contains(' '))
                {
                    return s.Split(' ');
                }
                else
                {
                    return new string[] { s };
                }
            }
            catch
            {
                return null;
            }
        }
        // =======  Maybe need to use?
    }
}